

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <meta charset="UTF-8">
    <link href="css/style.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>

    <script src="js/mqtt.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="js/layer/layer.js"></script>
    <script type="text/javascript" src="js/vue.min.js"></script>
    <!-- 加载百度地图基础口 -->
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ZQVKW0dvz0tgMy6ZytmY5RxZ"></script>
    <!-- 加载百度地图样式信息窗口 -->
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/SearchInfoWindow/1.5/src/SearchInfoWindow_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.5/src/SearchInfoWindow_min.css" />
    <!-- 加载城市列表 -->
    <script type="text/javascript" src="http://api.map.baidu.com/library/CityList/1.2/src/CityList_min.js"></script>
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js"></script>
    <script type="text/javascript"
            src="http://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js"></script>
    <style>
        .fire-tip {
            text-align: center;
            width: 100%;
            font-size: 44px;
            color: #ff0000;
            text-shadow: 0 0 1px #ffffff;
        }

        .fire-address {
            text-align: center;
            width: 100%;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.8);
            margin-top: 44px;
        }

        .fire-handle {
            display: block;
            text-align: center;
            background: #00BFF0;
            color: #ffffff;
            border-radius: 20px;
            font-size: 14px;
            width: 80px;
            height: 40px;
            line-height: 40px;
            margin: 24px auto;
            text-decoration: none
        }

        .fire-handle:hover {
            background: #06a2ca;
        }

        .container {
            position: fixed;
            left: 50%;
            top: 50%;
            margin-top: -160px;
            margin-left: -160px;
            width: 100%;
            height: 320px;
            z-index: 9999;
            display: none;
        }

        .container canvas {
            display: block;
            position: absolute;
            left: 0;
            top: -9px;
        }

        /* 保持大小不变的小圆圈  */
        .dot {
            position: absolute;
            width: 72px;
            height: 72px;
            left: 172px;
            top: 172px;
            background: url(./images/shebei.gif) no-repeat;
            background-size: 100%;
        }

        /* 产生动画（向外扩散变大）的圆圈  */
        .pulse,
        .pulse-big {
            position: absolute;
            width: 420px;
            height: 420px;
            border: 2px solid #EF2D02;
            background: rgba(239, 45, 2, 0.8);
            border-radius: 50%;
            z-index: 100;
            opacity: 0;
        }

        .pulse {
            background: rgba(239, 45, 2, 0.6) !important;
            -webkit-animation: warn 0.9s ease-out;
            -moz-animation: warn 0.9s ease-out;
            animation: warn 0.9s ease-out;
            -webkit-animation-iteration-count: infinite;
            -moz-animation-iteration-count: infinite;
            animation-iteration-count: infinite;
            box-shadow: 1px 1px 30px #EF2D02;
        }

        .pulse-big {
            background: rgba(239, 45, 2, 0.6) !important;
            -webkit-animation: warn1 0.9s ease-out;
            -moz-animation: warn1 0.9s ease-out;
            animation: warn1 0.9s ease-out;
            -webkit-animation-iteration-count: infinite;
            -moz-animation-iteration-count: infinite;
            animation-iteration-count: infinite;
            box-shadow: 1px 1px 30px #EF2D02;
        }

        .center-map {
            width: 42.77778rem;
            height: 27.32323rem;
            border: 1px solid #43dcff;
            margin-bottom: .10101rem;
            padding: .10101rem;
            box-sizing: border-box;
        }

        @keyframes warn {
            0% {
                -moz-transform: scale(0);
                transform: scale(0);
                opacity: 1;
            }

            100% {
                -moz-transform: scale(1);
                transform: scale(1);
                opacity: 0;
            }
        }

        @keyframes warn1 {
            0% {
                -o-transform: scale(0);
                transform: scale(0);
                opacity: 1;
            }

            100% {
                -o-transform: scale(0.6);
                transform: scale(0.6);
                opacity: 0;
            }
        }
    </style>
    <style type="text/css">
        body, html {
            width: 100%;
            height: 100%;
            overflow: hidden;
            margin: 0;
        }
        #allmap {height: 100%; width: 100%;overflow: hidden;}
        .music_icon{
            position: absolute;
            right:16px;
            top:50px;
            width:35px;
            height:35px;
            background:white;
            z-index: 100000;
            border-radius: 5px;
        }
        .music_icon img{
            width:100%;
        }
    </style>

</head>
<body >
<div class="music_icon" title="静音">
    <img id="music_icon" src="./images/mp3/on.png" alt="#">
</div>
<div  onclick="showInfo()" id="allmap"></div>
<div class="container" onclick="hidedot()">
    <div class="dot"></div>
    <div class="pulse"></div>
    <div class="pulse-big"></div>
</div>
<audio src="baojin.mp3" loop="loop" controls="controls" preload id="music1" >
</audio>

</body>
</html>


<script type="text/javascript">
    var audioActive = false;
    var audioNums = 0;
	
    $("#music_icon").click(function () {
        $(this).attr('src',audioActive?'./images/mp3/on.png':'./images/mp3/off.png');
        $("#music1")[0].volume = audioActive?0:1;
        if(audioNums<1){
            hidedot();
            audioNums ++;
        };
        audioActive = !audioActive;
    })

    //播放警报
    function playError(){
        console.log("播放警报")
        let audio = document.getElementById('music1');
        $('.container').show();
        audio.play();// 这个就是播放
    };

    //隐藏警报
    function hidedot() {
        console.log("隐藏警报")
        $('.container').hide();
        let audio = document.getElementById('music1');
        audio.pause();// 这个就是暂停
		showInfo();
    }

    $(document).ready(function () {

        $('.pop-close').click(function () {
            $('.bgPop3,.pop3').hide();
        });
        $('.click_pop3').click(function () {
            $('.bgPop3,.pop3').show();
        });
    })



    //百度地图API功能
    //创建地图实例
    var map = new BMap.Map("allmap", { mapType: BMAP_HYBRID_MAP });
    // var point = new BMap.Point(116.403694, 39.927552);  // 创建点坐标
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);  // 初始化地图,设置中心点坐标和地图级别
    // map.centerAndZoom(point, 5);                 // 初始化地图，设置中心点坐标和地图级
    map.setCurrentCity("深圳");          // 设置地图显示的城市 此项是必须设置的
    map.enableScrollWheelZoom();

    map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件 */
    map.addControl(new BMap.MapTypeControl({ mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP] }));     //卫星图
//鼠标单击事件函数
    function showInfo(){
		console.log("点击事件");
		let that=this;
		var deviceSn=localStorage.getItem("deviceSn")
		var jingdu=localStorage.getItem("jingdu")
		var weidu=localStorage.getItem("weidu")
		 console.log("deviceSn:"+deviceSn+" jingdu:"+jingdu+" weidu:"+weidu);
		if((deviceSn==null)||(jingdu==null)||(weidu==null))
		return;
	
		 $.ajax({
                    type: "post",
                    dataType: "json",
                    url:liufengtec_url+"/api/binder/getBinderOperatorByDeviceSn",
                    async: true,
                    crossDomain: true,
                    data:{
                        devicesn:deviceSn,
						userid:localStorage.getItem("userid"),
						token:localStorage.getItem('token') 
                    },
                    success: function (res) {
                        console.log(res);
						if(res.errorcode>0)
						return;
						var binder=res.binderDefault;
						 var markers = [];
						var pt = new BMap.Point(jingdu, weidu);
						map.centerAndZoom(pt, 11);
                            var myIcon = new BMap.Icon('./images/icon01.png', new BMap.Size(41, 53));
                            let marker = new BMap.Marker(pt, { icon: myIcon })
                            let opts = {
                                width: 200,     // 信息窗口宽度
                                height: 150,     // 信息窗口高度
                                title: `mac:${binder.deviceSn}` // 信息窗口标题
                            }
						 let msg = `联系人:${binder.userName}<br/>
                联系人手机:${binder.userPhone}
                <br/>
                地址:${binder.address}<br/>备注:${binder.deviceDesc}`
                            let infoWindow = new BMap.InfoWindow(msg, opts);  // 创建信息窗口对象
                           map.openInfoWindow(infoWindow,pt); //开启信息窗口
							console.log("openinfo");
 $('.container').hide();
        let audio = document.getElementById('music1');
        audio.pause();// 这个就是暂停
                    }
                });
	}
	
	//鼠标单击事件
	//map.addEventListener("click", showInfo);




</script>

<script>
    var isConnect = false;
	var waringDevice=null;
    function getClient() {
        clientId = 'yk/yd/web/msg/wka/' + Math.random().toString(16).substr(2, 8);
        return new Paho.MQTT.Client(hostname, port, clientId);
    }

    // var hostname = 'www.yunkongsz.com', //'192.168.1.2',
    var hostname = 'www.yunkongsz.com', //'192.168.1.2',
    liufengtec_url = "https://mqtt.dyad888.com"

        port = 61623,
        // clientId = 'yk/yd/web/hy/' + Math.random().toString(16).substr(2, 8),
        clientId = 'yk/yd/web/msg/wka/' + Math.random().toString(16).substr(2, 8),
        timeout = 5,
        keepAlive = 100,
        cleanSession = true,
        ssl = false,
        userName = 'admin',
        password = 'password',
        // topic = 'yk/yd/web/msg/hy/#';
        topic = 'yk/yd/web/msg/wka/#';
    let client = getClient();
    var listDistrict = new Vue({
        el: '#list-district',
        data: {
            userInfo:JSON.parse(localStorage.getItem('userInfo')?localStorage.getItem('userInfo'):"{}"),
            districts: [],
            backId: [],
            audioActive:false,
        },
        created() {
            this.read()
        },
        methods: {
            read: function () {
                let that = this
                let {userId:userid="",token=""} = this.userInfo;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url:liufengtec_url+"/api/device/getAllDeviceList",
                    async: true,
                    crossDomain: true,
                    data:{
                        userid,token
                    },
                    success: function (data) {
                        console.log(data);
                        if(data.token !== localStorage.getItem('token')){
                            parent.login();
                        }
                        that.districts = data.deviceList?data.deviceList:[];
                        let list = that.districts
                        // console.log("=============>"+JSON.stringify(that.districts))
                        let MAX = list.length;
                        let markers = [];
                        let pt = null;


                        for (let i = 0; i < MAX; i++) {

                            if(i==0){
                                let pt = new BMap.Point(list[i].jingdu, list[i].weidu);
                                map.centerAndZoom(pt, 14);
                            }
                            pt = new BMap.Point(list[i].jingdu, list[i].weidu);
                            var myIcon = new BMap.Icon('./images/icon01.png', new BMap.Size(41, 53));
                            let marker = new BMap.Marker(pt, { icon: myIcon })
                            let opts = {
                                width: 200,     // 信息窗口宽度
                                height: 150,     // 信息窗口高度
                                title: `mac:${list[i].deviceSn}` // 信息窗口标题
                            }
                            let msg = `联系人:${list[i].adminName}<br/>
                联系人手机:${list[i].adminPhone}
                <br/>
                地址:${list[i].address}<br/>备注:${list[i].deviceDesc}`
                            let infoWindow = new BMap.InfoWindow(msg, opts);  // 创建信息窗口对象
                            marker.addEventListener("click", function () {
                                marker.openInfoWindow(infoWindow, pt); //开启信息窗口
                            });
                            markers.push(marker);
                        }

                        var markerClusterer = new BMapLib.MarkerClusterer(map, { markers: markers });
                    }
                });
                this.getWsPlugin()
            },
            getWsPlugin(){
                //WebSocket
                var ws = null;
                const WebSocketUrl = 'wss://mqtt.dyad888.com/websocket';
                //判断当前浏览器是否支持WebSocket
                if ('WebSocket' in window) {
                    ws = new WebSocket(WebSocketUrl);
                } else if('MozWebSocket' in window){
                    ws = new MozMozWebSocket(WebSocketUrl);
                }else {
                    alert('您的浏览器不支持实时推送数据');
                };

                //连接成功建立的回调方法 发送心跳包
                ws.onopen = function (event) {
                    console.log("当前已连接ws")
                    setInterval (sendShock(), 10000);
                }

                //连接发生错误的回调方法
                ws.onerror = function () {
                    console.log("当前ws连接错误")
                };

                //接收到消息的回调方法
                ws.onmessage = function (event) {
                    console.log("接受带ws消息:",event)
                    setMessageInnerHTML(event.data);
                }

                //连接关闭的回调方法
                ws.onclose = function () {
                    console.log("ws连接关闭:")
                }

                //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
                window.onbeforeunload = function () {
                    ws.close();
                }

                //做具体操作
                const setMessageInnerHTML = (message)=>{
                    let [ , str ] = message?.split(":");
                    if(message.indexOf("报警信息")>-1){
                        this.messageSuccess( this.getUrlParam(str) );
                    }else if(message.indexOf("指令信息")>-1){
                        let { cmd='' } = this.getUrlParam(str);
                        if(cmd == 1) {
                            hidedot();
                            console.log("执行清除报警信息")
                        }else{
                            console.log("执行指令信息信息")
                        }
                    }else{
                        console.log(message)
                    }
                }

                //发送ws心跳包
                const sendShock = ()=>ws.send("shock");
            },
            getwss: function () {
                //建立客户端实例
                var options = {
                    invocationContext: {
                        host: hostname,
                        port: port,
                        path: client.path,
                        clientId: clientId
                    },
                    timeout: timeout,
                    keepAliveInterval: keepAlive,
                    cleanSession: cleanSession,
                    useSSL: ssl,
                    userName: userName,
                    password: password,
                    onSuccess: onConnect,
                    onFailure: function (e) {
                        console.log(e);
                    }
                };
                client.connect(options);
                //连接服务器并注册连接成功处理事件
                function onConnect() {
                    isConnect=true;
                    console.log("onConnected");
                    client.subscribe(topic);

                }
                client.onConnectionLost = onConnectionLost;
                //注册连接断开处理事件
                client.onMessageArrived = onMessageArrived;
                //注册消息接收处理事件
                var that = this;
                function onConnectionLost(responseObject) {
                    if (responseObject.errorCode !== 0) {
                        isConnect=false;
                        console.log("onConnectionLost:" + responseObject.errorMessage);
                        console.log("连接已断开");
                        that.reConnect();
                    }
                }
                let indexMessage = 0
                var thatD=this;
                function onMessageArrived(message) {
                    var dataS=message.payloadString;
                    var data = JSON.parse(dataS);
                    console.log("devinfo---------------------------------------------",devinfo)
                    var devinfo=JSON.parse(data.msg);
                    var devData=devinfo.devInfo;
                    var deviceMacD=devData.deviceSn;

                    var list=thatD.districts;
                    console.log("=============>"+JSON.stringify(deviceMacD))
                    if(list==undefined||list==null||list.length<1){
                        return;
                    }
                    var MAX=list.length;
                    var hasDevice=false;
                    for (let i = 0; i < MAX; i++) {
                        var deviceData=list[i];
                        console.log(" deviceData.deviceMac====> "+deviceData.deviceSn+" deviceMacD = "+deviceMacD);
                        if(deviceData.deviceSn==deviceMacD){
                            hasDevice=true;
                            break;
                        }
                    }
                    console.log(" hasDevice====> "+hasDevice);
                    if(!hasDevice){
                        return;
                    }

                    $('.container').show()
                    var audio = document.getElementById('music1');
                    if (audio !== null) {
                        //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
                        if (audio.paused) {
                            audio.play();//audio.play();// 这个就是播放
                        }
                    }
                    console.log("message="+message.payloadString);
                    indexMessage++

                    let classDev = 'devp_' + indexMessage
                    if (indexMessage == 21) {
                        indexMessage--
                        $("#Introduction_Box p:last").remove()
                    }
                console.log(devinfo);
                    
               
                    var pt = new BMap.Point(devinfo.devInfo.jingdu, devinfo.devInfo.weidu);
                    map.centerAndZoom(pt, 16);
                    parent.addAlarmMsg(data.msg);

                    //           let impressionHtml = `<p class="${classDev}">
                    //  ${data.msg.warmTime} &nbsp;&nbsp;异常消息：${data.msg.errMsg} &nbsp;&nbsp;设备MAC：${data.msg.devInfo.device_mac} &nbsp;&nbsp;设备名称：${data.msg.devInfo.device_des}
                    // &nbsp;&nbsp;联系人：${data.msg.devInfo.device_phone} &nbsp;&nbsp; 设备地址：${data.msg.devInfo.device_address}  </p>`
                    //           $('#Introduction_Box').prepend(impressionHtml)
                    //           $('#Introduction_Box p:first-child').on("click", function () {

                    //           });
                }
            },
            load: function (event) {
                console.log(event)
                var current = {
                    level: 0,
                    parentId: 0,
                    id: 0,
                    childCount: 0,
                    first: 0
                };
                if (event) {
                    current = this.districts[$(event.target).attr(
                        'data-index')];
                    let list = current.devData
                    $('#title_name').text(current.city)
                    $('#citydev_list').html('')
                    var MAX = list.length;
                    var markers = [];
                    var pt = null;
                    var ptlist = []
                    var i = 0;
                    for (; i < MAX; i++) {
                        pt = new BMap.Point(list[i].jingdu, list[i].weidu);
                        ptlist.push(pt)
                        markers.push(new BMap.Marker(pt));
                        let html = `<p>设备mac：${list[i].deviceSn} &nbsp;&nbsp; 设备描述：${list[i].deviceDesc}  &nbsp;&nbsp; 设备地址:${list[i].address} </p>`
                        $('#citydev_list').append(html)
                    }
                    $('#citydev_list p').each(function (index, element) {
                        $(element).on("click", function () {
                            // map.panTo(ptlist[index]); //转到该点位置
                            map.centerAndZoom(ptlist[index], 20);
                        });
                    })
                    // var markerClusterer = new BMapLib.MarkerClusterer(map, { markers: markers });
                }
            },
            back: function () {
                var id = this.backId.pop();
                if (id == null)
                    return;
                var _this = this;

            },
            reConnect: function () {
                var that = this;
                setTimeout(function connectMqtt() {
                    console.log("connectMqtt");
                    var state = navigator.onLine
                    console.log("state=" + state);
                    if (!state) {
                        alert("网络异常！")
                        that.reConnect();
                        return
                    }
                    console.log("client = " + isConnect);
                    if (!isConnect) {
                        client = getClient();
                        that.getwss();
                        that.reConnect();
                    }
                }, 30 * 1000);

            },

            //获取地址携带的参数
            getUrlParam(url='') {
                //获取url中"?"符后的字符串包括‘？’ ，window.location.href获取的是url完整的字符串
                var theParam = new Object();
                if(!url)return theParam
                let strs = url.split("&"); //将获取到的字符串从&分割，输出参数数组，即输出[参数1=xx,参数2=xx,参数3=xx,...]的数组形式
                for(var i = 0; i < strs.length; i ++) { //遍历参数数组
                    theParam[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); //这里意思是抽取每个参数等号后面的值，unescape是解码的意思
                }
                return theParam; //返回参数值
            },

            async messageSuccess(device){
                console.log("触发es回调事件了",this.districts,device);
                let hasDevice = false;
                for(let i=0;i<this.districts.length;i++){
                    let obj = this.districts[i];
                    if(obj.deviceSn==device.devicesn){
                        device.jingdu = obj.jingdu;
                        device.weidu = obj.weidu
                        hasDevice=true;
                        break;
                    }
                };

                if(!hasDevice)return false;
                playError();
				   var  deviceSn=device.devicesn;
				   var jingdu=device.jingdu;
				   var weidu=device.weidu;
				  localStorage.setItem("deviceSn",deviceSn);
				  localStorage.setItem("jingdu",jingdu);
				  localStorage.setItem("weidu",weidu);
				   console.log(deviceSn);
                var pt = new BMap.Point(device.jingdu, device.weidu);
                map.centerAndZoom(pt, 16);
                // await this.getInfos(device.devicesn);

                // parent.addAlarmMsg(device);
            },

            getInfos(devicesn){
                let _this = this;
                let {userId:userid="",token=""} = this.userInfo;
                return new Promise(resolve=>{
                    $.ajax({
                        method:"POST",
                        dataType: "json",
                        url:liufengtec_url+"/api/msg/getDeviceListByDeviceSn",
                        data:{
                            devicesn,
                            userid,
                            token
                        },
                        async: "true",
                        success: function (res) {
                            let {token,msgList=[]} = res;
                            console.log(res,'res--------',msgList)
                            if(token !== localStorage.getItem('token')){
                                parent.login();
                            }
                            resolve(msgList)
                        },
                        error(err){
                            console.log(err)
                        },
                    });
                })
            },
        }
    });
    $(function () {
        listDistrict.load();
        $('#return').click(function () {
            listDistrict.back();
        });
    });


</script>

<script>
    function centerMap(dataS){
        let pt = new BMap.Point(dataS.jingdu, dataS.weidu);
        map.centerAndZoom(pt, 18);


    }

</script>
	
